'''   Copyright [八月不落东方叶] [name of copyright owner]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
'''



import sqlite3

def sort2(a):                                         #冒泡排序
    for i in range(len(a)):
        for j in range(i, len(a)):
            if a[i] > a[j]:
                a[i], a[j] = a[j], a[i]
            if len(a)>=2:
                if a[-1] < a[-2]:
                    a[-1],a[-2]=a[-2],a[-1]
    return a

def newID():                                                         #给新任务用户分配ID（数据库内按递增顺序，ID为缺失的第一项，返回ID
    sel = "SELECT id FROM task"
    db = sqlite3.connect('data.db')
    cur = db.cursor()
    cur.execute(sel)
    db.commit()
    a=cur.fetchall()
    cur.close()
    db.close()
    if len(a) == 0:
        return 1
    c=[]
    for i in a:
        i=i[0]
        c.append(i)
    c.sort()
    flag = True
    for i in range(len(c)):
        if c[i]!=1 and flag == True:
            d=1
            flag = False
            break
        elif i!=0:
            if c[i-1]+1 != c[i]:
                flag = False
                d=c[i-1]+1
                break
        else:
            flag = False
            d=c[-1]+1
    return d

def creative(list1):                                                  #向数据库注入新任务（输入参数为列表，包含所有字段）
    ins = "INSERT INTO task VALUES(?,?,?,?,?,?)"
    id = list1[0]
    name = list1[1]
    old_path = list1[2]
    new_path = list1[3]
    retain_num = list1[4]
    status = list1[5]
    try:
        db = sqlite3.connect('data.db')
        cur = db.cursor()
        cur.execute(ins,(id,name,old_path,new_path,retain_num,status))
        db.commit()
        cur.close()
        db.close()
        return 1
    except:
        db.rollback ()
        return 0

def drop(b):                                                  #数据库任务删除
    try:
        db = sqlite3.connect('data.db')
        cur = db.cursor()
        cur.execute("DELETE FROM task where id = ? or name = ?",(b,b))
        db.commit()
        cur.close()
        db.close()
        return 1
    except:
        return 0

def select(b): 
    try:                                                       #数据查询(输入参数统一为用户名或ID，空值为查询所有)
        db = sqlite3.connect('data.db')
        cur = db.cursor()
        if b == "":
            sel = "SELECT * FROM task"
            cur.execute(sel)
        else:
            sel = "SELECT * FROM task where id == ? or name == ?"
            cur.execute(sel,(b,b))  
        db.commit()
        a=cur.fetchall()
        if len(a) > 1:
            a=sort2(a)
        cur.close()
        db.close()
        return a
    except:
        return 0
    '''elif i == 4:
        up = "UPDATE task SET newtime= ? where name == ? or id == ?"
        cur.execute(up,(a,b,b))
    '''

def change(a,i,b):                                                         #修改数据
    try:
        db = sqlite3.connect('data.db')
        cur = db.cursor()
        if i == 1:
            up = "UPDATE task SET name= ? where name == ? or id == ?"
            cur.execute(up,(a,b,b))
        elif i == 2:
            up = "UPDATE task SET old_path= ? where name == ? or id == ?"
            cur.execute(up,(a,b,b))
        elif i == 3:
            up = "UPDATE task SET new_path= ? where name == ? or id == ?"
            cur.execute(up,(a,b,b))
        elif i == 4:
            up = "UPDATE task SET retain_num= ? where name == ? or id == ?"
            cur.execute(up,(a,b,b))
        elif i == 5:
            if a == 'y':
                a = '┗|｀O′|┛ 嗷~~'
            elif a == 'n':
                a='-------------'
            up = "UPDATE task SET status= ? where name == ? or id == ?"
            cur.execute(up,(a,b,b))
        db.commit()
        cur.close()
        db.close()
        return 1
    except:
        return 0
    
def off():                                                             #关闭，执行成功返回'1',执行失败返回'0'
    try:
        db = sqlite3.connect('data.db')
        cur = db.cursor()
        cur.execute("UPDATE task SET status='-------------'")
        db.commit()
        cur.close()
        db.close()
        return 1
    except:
        return 0

def on():                                                              #启动，执行成功返回'1',执行失败返回'0'
    try:
        db = sqlite3.connect('data.db')
        cur = db.cursor()
        cur.execute("UPDATE task SET status='┗|｀O′|┛ 嗷~~'")
        db.commit()
        cur.close()
        db.close()
        return 1
    except:
        return 0

